package com.example.filter;



import com.example.domain.LoginUser;
import com.example.domain.User;
import com.example.mapper.UserMapper;
import com.example.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class TokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserMapper userMapper;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        //如果没有token需要做的就是放行，因为后面security的过滤器肯定过不去
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("token") == null){
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //从数据库中找到这个数据
        User user = userMapper.getOne(userId);
        if (Objects.isNull(user)){
            throw new RuntimeException("token非法");
        }
        LoginUser user1 = (LoginUser) request.getSession().getAttribute("user");
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(user1,null,user1.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(upat);
        filterChain.doFilter(request,response);
    }
}
